"""
Cookie：指某些网站为了辨别用户身份、进行回话跟踪而存储在用户本地的数据（通常经过加密，session）
Cookie是有服务器段生成，发送给客户端浏览器，浏览器会将Cookie的key/value保存，下次请求同一网站时就发送该Cookie给服务器（需浏览器开启cookie）
Cookie是存储再浏览器中的一段纯文本信息，建议不要存储敏感信息（如密码），是给予域名安全的，不同域名的Cookie不能互相访问（可以用本地计算机作为中转保存从而跨域）
Cookie信息可以从request中读取

"""

from flask import Flask, make_response, request

app = Flask(__name__)


@app.route('/')
def hello():
    return "Hello world"


@app.route('/login')
def login():
    """登陆成功后使用cookie保存用户的登陆信息"""
    # 1.创建响应对象,并窜入需要返回的内容，该内容可以是其他方式获得,如放在文末的例子
    response = make_response("login success")
    # 2.使用响应对象中的 set_cookie方法设置用户信息（键值对）
    # 参数1：key  参数2：value  参数3：max_age代表过期时长（有效期）
    response.set_cookie('user_name', 'laowang', max_age=3333)
    response.set_cookie('user_id', '1', max_age=3333)
    # 3.返回响应对象,这里（返回值有时为字符串，如oneday中代码）最后都会包装（flask服务器会自动完成这步）成一个响应对象传给响应体
    return response


# 127.0.0.1:5000/index -- request
@app.route('/index')
def index():
    """再次请求首页时获取cookie中的用户信息"""
    user_name = request.cookies.get("user_name", '')
    user_id = request.cookies.get('user_id', '')
    return 'index  %s  -----  %s' % (user_name, user_id)


@app.route('/login_out')
def login_out():
    """退出登录删除cookie中保存的用户信息"""
    # 1.构建响应对象
    response = make_response("login_out success")
    # 2.借助响应的对象中的delete_cookie方法删除cookie中的数据
    response.delete_cookie('user_name')
    response.delete_cookie('user_id')
    # 3.返回响应对象
    return response


if __name__ == '__main__':
    app.run(debug=True)

"""
make_response源码：
def make_response(*args):
Sometimes it is necessary to set additional headers in a view.  Because
    views do not have to return response objects but can return a value that
    is converted into a response object by Flask itself, it becomes tricky to
    add headers to it.  This function can be called instead of using a return
    and you will get a response object which you can use to attach headers.

    If view looked like this and you want to add a new header::

        def index():
            return render_template('index.html', foo=42)

    You can now do something like this::

        def index():
            response = make_response(render_template('index.html', foo=42))
            response.headers['X-Parachutes'] = 'parachutes are cool'
            return response

    This function accepts the very same arguments you can return from a
    view function.  This for example creates a response with a 404 error
    code::

        response = make_response(render_template('not_found.html'), 404)

    The other use case of this function is to force the return value of a
    view function into a response which is helpful with view
    decorators::

        response = make_response(view_function())
        response.headers['X-Parachutes'] = 'parachutes are cool'

    Internally this function does the following things:

    -   if no arguments are passed, it creates a new response argument
    -   if one argument is passed, :meth:`flask.Flask.make_response`
        is invoked with it.
    -   if more than one argument is passed, the arguments are passed
        to the :meth:`flask.Flask.make_response` function as tuple.

    .. versionadded:: 0.6
    """
